import axios from 'axios'
import store from '@/store'
import { Toast } from 'vant'
// 根据环境不同引入不同api地址
import { baseApi } from '@/config'

import LocalStorage from '../model/localStorage.js'
import {interfaceUtils} from  '../model/interface.js'
// create an axios instance
const service = axios.create({
  baseURL: baseApi, // url = base api url + request url
  // withCredentials: true, // send cookies when cross-domain requests
  timeout: 5000, // request timeout
  // 静态请求头
  // headers: {
  //   "content-type": "application/json",
  //   "verify-type": "type",
  //  "login-token":LocalStorage.get('token') || interfaceUtils.login_token
  // },
})

// request拦截器 request interceptor
service.interceptors.request.use(
  config => {
    // 不传递默认开启loading
    if (!config.hideloading) {
      // loading
      Toast.loading({
        forbidClick: true
      })
    }
    // console.log("token1",LocalStorage.get('token') || interfaceUtils.login_token)
    if (LocalStorage.get('token')) {
      config.headers['login-token'] = LocalStorage.get('token')
    }else{
      config.headers['login-token'] =interfaceUtils.login_token
    }
    return config
  },
  error => {
    // do something with request error
    // console.log(error) // for debug
    return Promise.reject(error)
  }
)
// respone拦截器
service.interceptors.response.use(
  response => {
    Toast.clear()
    const res = response.data
    // console.log("response",response)
    // return Promise.resolve(res)
    // if (res.status && res.status !== 200) {
    //   // 登录超时,重新登录
    //   // if (res.status === 401) {
    //   //   store.dispatch('FedLogOut').then(() => {
    //   //     location.reload()
    //   //   })
    //   // }
    //   return Promise.reject(res || 'error')
    // } else {
    //   return Promise.resolve(res)
    // }
    if(res.code == 200){
      
      return Promise.resolve(res)
    }else if(res.code == 201){
      // 重新登陆
      store.dispatch('setToken', '')
      store.dispatch('setUserInfo', '')
      LocalStorage.clear()
      // Toast.fail({
      //   message:"Login expires , please login agin"
      // })
      // setTimeout(() => {
        location.reload()
      // }, 3000);
      return Promise.reject(res.message)
     
     
     
    
    
    }else{
      return Promise.reject(res.message)
     
    }
  },
  error => {
    
    Toast.clear()
    // console.log('err' + error) // for debug
    return Promise.reject(error)
  }
)

export default service
